<template>
	<view class="custom-header-container">
		<view class="custom-header">
			<view class="header-left">
				<view class="" v-if="isHomepage">
					今生永恒网——始于2006
				</view>
				<view class="" v-else>
					<text class="header-icon" @click="goHome">🏠</text> 
					<text class="header-icon" @click="goBack">↩</text>
				</view>
			</view>

			<view class="header-center"></view>

			<view class="header-right">
				<template v-if="isLoggedIn">
					<template v-if="isHomepage">
						<text class="header-user-nickname">{{ userInfo?.nickname || '用户' }}</text>
						<view class="header-button" @click="handleManageCenter">管理</view>
					</template>
					<template v-else>
						<text class="header-user-phone">{{ userInfo?.nickname || '用户' }}</text>
						<text class="header-link" @click="logoutFun">退出</text>
						<text class="header-link" @click="handleManageCenter">管理中心</text>
					</template>
				</template>
				<template v-else>
					<template v-if="isHomepage">
						<text class="header-link" @click="handleLogin">登录</text>
						<text class="header-link" @click="handleRegister">免费注册</text>
					</template>
					<template v-else>
						<text class="header-link" @click="handleLogin">登录</text>
						<text class="header-link" @click="handleRegister">免费注册</text>
					</template>
				</template>
			</view>
		</view>
		<!-- 遮罩层和弹窗 -->
		<view v-if="showLogin" class="modal-mask" @touchmove.stop.prevent>
			<view class="login-modal">
				<view class="modal-header">
					<view class="modal-tabs">
						<text :class="['modal-tab', loginTab === 0 ? 'active' : '']" @click="loginTab = 0">账号登录</text>
						<text :class="['modal-tab', loginTab === 1 ? 'active' : '']" @click="loginTab = 1">微信授权登录</text>
					</view>
					<text class="modal-close" @click="showLogin = false">×</text>
				</view>
				<view class="modal-body">
					<view v-if="loginTab === 0" style="width: 100%;">
						<input class="modal-input" placeholder="用户名/手机号" v-model="loginForm.username" />
						<input class="modal-input" placeholder="密码" type="password" v-model="loginForm.password" />
					</view>
					
					<view class="modal-btn-row" v-if="loginTab === 0">
						<button class="modal-btn primary" @click="loginFun">登录</button>
						<button class="modal-btn" @click="showLogin = false">取消</button>
					</view>
					<view class="modal-btn-row-wechat" v-else>
						<button class="modal-btn weChat" @click="toLog">
							<image src="/static/WeChat_icon.png" mode="aspectFill" style="width: 40rpx;height: 40rpx;margin-right: 10rpx;"></image>
							微信授权登录
						</button>
					</view>
					<view class="modal-footer-row">
						<text class="modal-link" @click="handleRegister">免费注册用户</text>
						<!-- <text class="modal-link right">忘记密码?</text> -->
					</view>
				</view>
			</view>
		</view>
		
		<swiper class="banner" circular :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" v-if="bannerList.length > 0">
			<swiper-item v-for="(item, index) in bannerList" :key="index">
				<image :src="item.cover" mode="aspectFill" class="banner-image"></image>
			</swiper-item>
		</swiper>
	</view>
</template>

<script setup lang="ts">
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { login, getUserInfo, logout, scanLogin, oaLogin, oaAuthBind } from '@/api/user.js';
	import { setToken, getToken } from '@/utils/token.js';
	import {
		onMounted,
		reactive,
		ref,
		toRaw,
		watch
	} from 'vue';
	
	
	const showLogin = ref(false)
	const loginTab = ref(0);
	const loginForm = ref({
		username: '',
		password: '', 
		phone: '',
		sms: ''
	});
	const isLoggedIn = ref(false)
	const userInfo = ref<{
		[key: string]: any
	}>({})
	// Define props accepted by the component
	const props = defineProps({
		isHomepage: {
			type: Boolean,
			default: false // Default to non-homepage
		},
		bannerList: {
			type: Array,
			default: []
		}
	});

	// Define events emitted by the component
	

	// --- Event Handlers (Emit events to parent) ---
	const goHome = () => {
		console.log('Header: Emitting goHome');
		uni.navigateTo({
			url: '/pages/index/index'
		})
	};

	const goBack = () => {
		console.log('Header: Emitting goBack');
		uni.navigateBack({
			delta: 1
		})
	};
	
	// 显示登录弹窗
	const handleLogin = () => {
		console.log('Header: Emitting login');
		// emit('login');
		showLogin.value = true
	};
	
	// 去注册
	const handleRegister = () => {
		console.log('Header: Emitting register');
		// emit('register');
		uni.navigateTo({
			url: '/pages/register/index'
		})
	};

	
	// 去管理中心
	const handleManageCenter = () => {
		console.log('Header: Emitting manageCenter');
		// emit('manageCenter'); // For non-homepage "管理中心" link
		uni.navigateTo({
			url: '/pages/graveyardManage/manageCenter/index'
		})
	};
	
	// 登录
	const loginFun = () => {
		let obj = {
			account: loginForm.value.username.trim(),
			password: loginForm.value.password,
			terminal: 3
		}
		login(obj).then(res=>{
			console.log(res)
			if(res.code == 1){
				setToken(res.data.token)
				uni.setStorageSync('userInfo', res.data)
				userInfo.value = res.data
				isLoggedIn.value = true
				showLogin.value = false
				if(!res.data.openid){
					toLog()
				}
			}else{
				uni.showToast({
					title: res.msg,
					icon: 'none',
					duration: 1000
				})
			}
		}).catch(error=>{
			console.log(error)
		})
	}
	// 退出登录
	const logoutFun = () => {
		uni.showModal({
			title: '提示',
			content: '您确定要退出？',
			success: function (res) {
				if (res.confirm) {
					console.log('用户点击确定');
					logout().then(result=>{
						console.log(result)
						if(result.code == 1){
							uni.removeStorageSync('User-Token')
							uni.removeStorageSync('userInfo')
							isLoggedIn.value = false
							userInfo.value = {}
							uni.navigateTo({
								url: '/pages/index/index'
							})
						}
					}).catch(error=>{
						console.log(error)
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
		
	}
	// 获取用户信息
	const getUserInfoFun = () => {
		getUserInfo().then(res=>{
			console.log(res)
			if(res.code == 1){
				uni.setStorageSync('userInfo', res.data)
				uni.setStorageSync('user_id', res.data.id)
				userInfo.value = res.data
				user_id.value = res.data.id
				console.log(toRaw(userInfo.value))
			} else if (res.code == 401){
				isLoggedIn.value = false
			}
		}).catch(error=>{
			console.log(error)
		})
	}
	const getQueryVariable = (variable) => {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return (false);
	}
	onLoad(async()=>{
		await getUserInfoFun()
		
		// await handleWeChatLogin()
	})
	onShow( async (options)=>{
		
		if(uni.getStorageSync('User-Token')){
			isLoggedIn.value = true
		}else{
			isLoggedIn.value = false
		}
		// if (options?.error_description) {
		//     uni.showToast({
		// 		title: `授权失败: ${options.error_description}`,
		// 		icon: 'none',
		// 		duration: 3000
		//     });
		// }
		let code = getQueryVariable('code')
		if (code) {
			if(getToken()){
				oaAuthBind({code}).then(res=>{
					console.log('res============',res)
					if(res.code == 1){
						setToken(res.data.token)
						getUserInfoFun()
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 1000
						})
					}
				}).catch(error=>{
					console.log('error===============',error)
					uni.showToast({
						title: error.msg,
						icon: 'none',
						duration: 1000
					})
				})
			}else{
				oaLogin({code}).then(res=>{
					console.log(res)
					if(res.code == 1){
						setToken(res.data.token)
						getUserInfoFun()
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}
				}).catch(error=>{
					console.log(error)
				})
			}
		}
	})
	
	
	// --- 配置 ---
	// !!! 重要：这些敏感信息不应该硬编码在前端，理想情况下从后端API获取或在构建时注入
	// 这里为了演示方便直接写出，实际项目中请注意安全
	const WECHAT_APP_ID = ref('wx36819d0881150fc8'); // 替换为你的微信公众号AppID
	
	// 授权后回调的H5页面地址，必须在微信公众平台配置的网页授权域名之下
	// 例如: https://m.yourdomain.com/auth/wechat-callback
	// 需要 URL Encode
	// const REDIRECT_URI = encodeURIComponent('https://client-grave.shengxuankj.com/web');
	const REDIRECT_URI = encodeURIComponent('https://cqjsyh.com/H5');
	
	const loading = ref(false);
	
	const handleWeChatLogin = () => {
	  // 1. 构造微信授权URL
	  // scope:
	  // - snsapi_base: 静默授权，用户无感知，只能获取openid
	  // - snsapi_userinfo: 需要用户手动同意，可以获取用户的基本信息
	  const scope = 'snsapi_userinfo';
	  const state = `STATE_${Date.now()}`; // 可选，用于防止CSRF攻击，后端可以校验
	
	  // 存储 state 到 localStorage，以便回调时校验 (可选但推荐)
	  uni.setStorageSync('wechat_oauth_state', state);
	
	  const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WECHAT_APP_ID.value}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
	
	  // 2. 重定向到微信授权页
	  // #ifdef H5
	  window.location.href = authUrl;
	  // #endif
	};
	
	
	const user_id = ref('')
	const toLog = () => {
		// return
		let code = getQueryVariable('code')
		if (code) {
			console.log(code);
			oaLogin({code}).then(res=>{
				console.log(res)
				if(res.code == 1){
					setToken(res.data.token)
					uni.setStorageSync('userInfo', res.data)
					uni.setStorageSync('user_id', res.data.id)
					userInfo.value = res.data
					user_id.value = res.data.id
				}
			}).catch(error=>{
				console.log(error)
			})
		} else {
			console.log('111111111111111111111111111111')
			let appid = "wx36819d0881150fc8" //项目appid
			let mainstate = Math.random()
			let url = encodeURIComponent('https://cqjsyh.com/H5') //这里的是回调地址要与申请的地址填写一致
			let scopes = "snsapi_userinfo" //表示授权的作用域，多个可以用逗号隔开，snsapi_base表示静默授权，snsapi_userinfo表示非静默授权
			let httpsUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=${scopes}&state=${mainstate}&connect_redirect=1#wechat_redirect`
			window.location.href = httpsUrl
		}
	}
</script>

<style scoped>
	/* Component specific styles */
	/* Use rpx for mobile adaptation */

	.custom-header-container {
		/* height: 88rpx; */
		/* Occupy the space */
		/* Removed position: fixed here, parent page will handle positioning */
	}

	.custom-header {
		/* Position fixed to stay at the top */
		/* position: fixed; */
		/* top: 0; */
		/* left: 0; */
		/* right: 0; Take full width */
		height: 88rpx;
		/* Standard header height */
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20rpx;
		/* Side padding */
		background-color: #fff;
		/* White background */
		border-bottom: 1rpx solid #eee;
		/* Subtle border */
		z-index: 100;
		/* Ensure header is on top of content */
		box-sizing: border-box;
		/* Include padding in height */
	}

	.header-left {
		display: flex;
		align-items: center;

		flex-shrink: 0;
		/* Prevent shrinking */
	}

	.header-icon {
		font-size: 40rpx;
		/* Adjust icon size */
		color: #333;
		margin-right: 30rpx;
		/* Space between icons */
		line-height: 1;
		/* Better vertical alignment for text icons */
	}

	.header-icon:last-child {
		margin-right: 0;
	}

	.header-center {
		flex-grow: 1;
		/* Allow center to take available space */
		text-align: center;
		/* No content in center for these specific headers, keep empty */
	}

	.header-right {
		display: flex;
		align-items: center;
		/* Adjust width or let content dictate */
		flex-shrink: 0;
		/* Prevent shrinking */
	}

	.header-user-phone {
		font-size: 26rpx;
		color: #ff9800;
		/* Orange color */
		margin-right: 15rpx;
		font-weight: bold;
	}

	.header-user-nickname {
		font-size: 26rpx;
		color: #333;
		/* Match sample image color */
		margin-right: 15rpx;
	}


	.header-link {
		font-size: 26rpx;
		color: #ff9800;
		/* Orange color for links */
		margin-left: 15rpx;
		/* Space between links */
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.header-link:first-child {
		margin-left: 0;
		/* No left margin for the first link */
	}

	.header-button {
		/* Style the "管理" button */
		font-size: 24rpx;
		/* Smaller text than links */
		color: #333;
		background-color: #eee;
		/* Light gray background */
		border: 1rpx solid #ccc;
		/* Subtle border */
		border-radius: 5rpx;
		padding: 5rpx 15rpx;
		/* Padding */
		margin-left: 15rpx;
		/* Space from nickname */
		line-height: 1.5;
		/* Adjust line height for vertical centering */
		display: flex;
		/* Use flex to center text */
		align-items: center;
		justify-content: center;
	}

	/* Add padding to page content to clear the fixed header */
	/* This should be applied to the main content container of each page using this header */
	/* Example in page style: padding-top: 88rpx; */
	
	
	.modal-mask {
		position: fixed;
		z-index: 99;
		left: 0; top: 0; right: 0; bottom: 0;
		background: rgba(0,0,0,0.45);
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.login-modal {
		width: 400px;
		max-width: 90vw;
		background: #fff;
		border-radius: 12px;
		box-shadow: 0 4px 24px rgba(0,0,0,0.18);
		padding: 0 0 24px 0;
		position: relative;
	}
	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 24px;
		height: 56px;
		border-bottom: 1px solid #f5e3c2;
		background: #fdf6e3;
		border-radius: 12px 12px 0 0;
	}
	.modal-tabs {
		display: flex;
		align-items: center;
	}
	.modal-tab {
		font-size: 18px;
		color: #b98c4b;
		padding: 0 16px;
		line-height: 56px;
		cursor: pointer;
	}
	.modal-tab.active {
		color: #e69c23;
		font-weight: bold;
		border-bottom: 2px solid #e69c23;
	}
	.modal-close {
		font-size: 28px;
		color: #b98c4b;
		cursor: pointer;
		margin-left: 12px;
	}
	.modal-body {
		width: 100%;
		padding: 24px 32px 0 32px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}
	.modal-input {
		width: 100%;
		height: 40px;
		margin-bottom: 16px;
		border: 1px solid #e5e5e5;
		border-radius: 4px;
		padding: 0 12px;
		box-sizing: border-box;
		font-size: 16px;
		background: #fafafa;
	}
	.modal-btn-row {
		width: 100%;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin-top: 8px;
		gap: 12px;
	}
	.modal-btn-row-wechat{
		width: 100%;
		display: flex;
		align-items: center;
		margin-top: 8px;
		gap: 12px;
		justify-content: center;
	}
	.modal-btn {
		min-width: 90px;
		height: 36px;
		border-radius: 4px;
		border: none;
		font-size: 16px;
		background: #f5f5f5;
		color: #666;
		margin-right: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 !important;
	}
	.modal-btn.primary {
		background: #ffb43a;
		color: #fff;
	}
	.weChat{
		background: #00a859;
		color: #fff;
	}
	.modal-footer-row {
		display: flex;
		/* justify-content: space-between; */
		justify-content: flex-end;
		align-items: center;
		margin-top: 12px;
		padding: 0 2px;
	}
	.modal-link {
		font-size: 14px;
		color: #b98c4b;
		cursor: pointer;
	}
	.modal-link.right {
		float: right;
	}
	
	/* 轮播图样式 */
	.banner {
		width: 100%;
		height: 300rpx;
	}
	.banner-image {
		width: 100%;
		height: 100%;
	}
</style>